package com.tanhua.server.service;

import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.mongo.TestSoulApi;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private TestSoulApi testSoulApi;

    @Autowired
    private MqMessageService mqMessageService ;

    public static final String CHECK_CODE = "CHECK_CODE_";

    public void sendMsg(String phone) {
        String code = RandomStringUtils.randomNumeric(6);
        System.out.println("你的验证码是："+code);
        redisTemplate.opsForValue().set(CHECK_CODE + phone, code, Duration.ofMinutes(5));
//        smsTemplate.sendSms(phone, code);
    }

    public Map<String, Object> veryfyCode(String phone, String verificationCode) {
        String code = redisTemplate.opsForValue().get(CHECK_CODE + phone);
        if (code == null || !code.equals(verificationCode)) {
            throw new RuntimeException("验证码错误");
        }
        redisTemplate.delete(CHECK_CODE + phone);

        boolean isNew = false;

        User user = userApi.findByPhone(phone);

        String type = "0101";

        if (user == null) {
            //表示该用户为新用户
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            Long id = userApi.saveUser(user);
            user.setId(id);
            isNew = true;

            String hxUser = "hx"+user.getId();
            String hxPassword = Constants.INIT_PASSWORD;
            user.setHxUser(hxUser);
            user.setHxPassword(hxPassword);
            userApi.update(user);
            testSoulApi.saveTest(user);  //新用户注册，则会保存三套灵魂测试题到mongodb
            type = "0102";
        }
        //检测是否冻结
        String reason = redisTemplate.opsForValue().get(Constants.FreezeLogin_KEY + user.getId());
        Long restTime = redisTemplate.opsForValue().getOperations().getExpire(Constants.FreezeLogin_KEY + user.getId(), TimeUnit.HOURS);
        if (reason != null) {
            throw new BusinessException("该用户处于冻结状态, 请联系客服处理", ErrorResult.freezeLoginError("\n 解除冻结剩余时间"+restTime+"小时"+"\n 冻结原因"+reason));
        }


        mqMessageService.sendLogService(user.getId(),type,"user","");

        Map<String,Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(claims);

        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        result.put("isNew",isNew);
        return result;
    }

}
